package dfs;

import model.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class App {

    public static void main(String[] args) {
        //    10
        // 1     20
        //2 3  22  23
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(1);
        root.right = new TreeNode(20);

        root.left.left = new TreeNode(2);
        root.left.right = new TreeNode(3);

        root.right.left = new TreeNode(22);
        root.right.right = new TreeNode(23);

        List<List<TreeNode>> res = new App().dfs(root);

        for (int i = 0; i < res.size(); i++) {
            String str = "第" + i + "层：";
            for (int j = 0; j < res.get(i).size(); j++) {
                str += res.get(i).get(j).val + ",";
            }
            System.out.println(str);
        }
    }

    public List<List<TreeNode>> dfs(TreeNode root) {
        List<List<TreeNode>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        travel(root, res, 0);
        return res;

    }

    public void travel(TreeNode root, List<List<TreeNode>> res, int level) {
        if (root == null) {
            return;
        }
        if (res.size() == level) {
            res.add(new ArrayList<>());
        }
        res.get(level).add(root);

        travel(root.left, res, level + 1);
        travel(root.right, res, level + 1);
    }
}
